#include "pir_sensor_sensitivity.h"
#include "systime.h"
#include "adc_driver.h"

#define SENSOR_UPDATE_TIME 20 // 单位ms,灵敏度检测更新时间

// 灵敏度阈值--单位，ADC分辨率
#define PIR_SENSITIVITY_THRESHOLD_HIGH 450   //2档 实际测量511
#define PIR_SENSITIVITY_THRESHOLD_LOW 600   //1档 实际测量663
#define PIR_SENSITIVITY_THRESHOLD_OFF 700   //0档 实际测量787

typedef enum
{
    STATE_INIT,
    STATE_NORMAL,
} run_state_e;

static struct
{
    timestamp_t time;
    run_state_e run_state;
    pir_sensitivity_e level; // 灵敏度
} pir_sensitivity_ctx;

static pir_sensitivity_e pir_sensor_sensitivity_level_get(void);

void pir_sensor_sensitivity_init(void)
{
    pir_sensitivity_ctx.run_state = STATE_INIT;
    pir_sensitivity_ctx.level = PIR_SENSITIVITY_HIGH;
}

pir_sensitivity_e get_pir_sensor_sensitivity(void)
{
    return pir_sensitivity_ctx.level;
}

void pir_sensor_sensitivity_task(void)
{
    switch (pir_sensitivity_ctx.run_state)
    {
    case STATE_INIT:
        pir_sensitivity_ctx.level = pir_sensor_sensitivity_level_get();
        relative_time_add_ms(&pir_sensitivity_ctx.time, SENSOR_UPDATE_TIME);
        printf("the SENSOR position:%d \r\n", pir_sensitivity_ctx.level);
        pir_sensitivity_ctx.run_state = STATE_NORMAL;
        break;
    case STATE_NORMAL:
        if (is_relative_time_timeout(&pir_sensitivity_ctx.time))
        {
            pir_sensitivity_ctx.level = pir_sensor_sensitivity_level_get();
            relative_time_add_ms(&pir_sensitivity_ctx.time, SENSOR_UPDATE_TIME);
        }
        break;

    default:
        break;
    }
}

static pir_sensitivity_e pir_sensor_sensitivity_level_get(void)
{
    uint16_t val = get_pir_sensor_sensitivity_val();
    if (val <= PIR_SENSITIVITY_THRESHOLD_LOW)
        return PIR_SENSITIVITY_HIGH;
    else if (val <= PIR_SENSITIVITY_THRESHOLD_OFF)
        return PIR_SENSITIVITY_LOW;
    else
        return PIR_SENSITIVITY_OFF;
}
